import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '../layouts/MainLayout.vue'
import ContractList from '../views/ContractList.vue'
import DetailPanel from '../views/DetailPanel.vue'

const routes = [
  {
    path: '/',
    component: MainLayout,
    redirect: '/contracts',
    children: [
      {
        path: '/contracts',
        name: 'ContractList',
        component: ContractList,
        meta: { requiresAuth: true }
      },
      {
        path: '/contracts/table',
        name: 'ContractTable',
        component: () => import('../views/ContractTable.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/contracts/detail',
        name: 'ContractDetail',
        component: () => import('../views/ContractDetail.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/detail-panel',
        name: 'DetailPanel',
        component: DetailPanel,
        meta: {
          title: '详情面板'
        }
      },
      {
        path: '/next-update',
        name: 'NextUpdate',
        component: () => import('../views/NextUpdate.vue'),
        meta: {
          title: '下次更新'
        }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated')
  
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router 